package org.bee.util;

import org.bee.model.BatchJob;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import java.util.Date;

/**
 * 抽象quartz调用
 *
 */
public abstract class AbstractQuartzJob implements Job
{
    private static final Logger log = LoggerFactory.getLogger(AbstractQuartzJob.class);

    /**
     * 线程本地变量
     */
    private static ThreadLocal<Date> threadLocal = new ThreadLocal<>();

    @Override
    public void execute(JobExecutionContext context) {
        BatchJob batchJob = new BatchJob();
        BeanUtils.copyProperties(context.getMergedJobDataMap().get(ScheduleUtils.TASK_PROPERTIES),batchJob);
        try{
            before(context, batchJob);
            doExecute(context, batchJob);
            after(context, batchJob, null);
        }catch (Exception e){
            log.error("任务执行异常  - ：", e);
            after(context, batchJob, e);
        }
    }

    /**
     * 执行前
     *
     * @param context 工作执行上下文对象
     * @param sysJob 系统计划任务
     */
    protected void before(JobExecutionContext context, BatchJob batchJob){
        threadLocal.set(new Date());
    }

    /**
     * 执行后
     *
     * @param context 工作执行上下文对象
     * @param sysJob 系统计划任务
     */
    protected void after(JobExecutionContext context, BatchJob batchJob, Exception e){
        Date startTime = threadLocal.get();
        threadLocal.remove();
        //todo 记录定时任务执行日志
    }

    /**
     * 执行方法，由子类重载
     *
     * @param context 工作执行上下文对象
     * @param sysJob 系统计划任务
     * @throws Exception 执行过程中的异常
     */
    protected abstract void doExecute(JobExecutionContext context, BatchJob batchJob) throws Exception;
}
